/**
 * 
 */
package com.munoor.dalai.server.servlets;

import java.io.IOException;

import javax.servlet.Filter;
import javax.servlet.FilterChain;
import javax.servlet.FilterConfig;
import javax.servlet.ServletException;
import javax.servlet.ServletRequest;
import javax.servlet.ServletResponse;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;

import com.munoor.dalai.server.model.User;

/**
 * @author Ilamah, Osho 31 March 2011
 */
public final class AuthorizationFilter implements Filter {

	// private FilterConfig filterConfig = null;

	@Override
	public void destroy() {
	}

	@Override
	public void doFilter(ServletRequest req, ServletResponse resp, FilterChain chain) throws IOException,
			ServletException {

		// if (true){ //authentication/authorisation check, passed?
		HttpServletRequest request = (HttpServletRequest) req;
		HttpServletResponse response = ((HttpServletResponse) resp);
		HttpSession session = request.getSession();
		User user = (User) (session.getAttribute("userid"));
		if (user == null) {
			// User not logged in or session invalid. Respond with HTTP/401
			System.out.println("User not logged in or session invalid. Responding with HTTP/401");
			response.sendError(HttpServletResponse.SC_UNAUTHORIZED, "Unauthourized");
		} else {
			// a user attribute is present. We need to run authorisation for requestURI
			String requestURI = request.getRequestURI();
			if (((requestURI.indexOf("admin") > -1) && (user.getUserType() > 0)) || (user.getUserType() > 2)) {
				// trying to access admin area from a normal account. Block   || user email not validated, inactive or frozen etc kind of user
				System.out.println("Authorisation blocked on level " + user.getUserType());
				response.sendError(HttpServletResponse.SC_UNAUTHORIZED, "Unauthourized");
			} else if ((requestURI.indexOf("users") > -1) && (requestURI.indexOf("users/" + user.getUserId() + "/") == -1)){
				//normal user access for active user but the authenticated user is requesting another users (id) resource
				//i.e. user A is access /users/B/*
				response.sendError(HttpServletResponse.SC_UNAUTHORIZED);
			}else{
				chain.doFilter(req, resp);
			}
			}
		}
	

	@Override
	public void init(FilterConfig config) throws ServletException {
		// filterConfig = config;
	}
}
